<template>
  <div class="shop-edit padding-top">
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="124px"
      label-position="right"
      class="demo-ruleForm"
    >
      <el-form-item label="店主用户名：">
        <el-input v-model="form.member_name" disabled></el-input>
      </el-form-item>
      <el-form-item label="公司名称：">
        <el-input v-model="form.store_owner"></el-input>
      </el-form-item>
      <el-form-item label="身份证号：">
        <el-input v-model="form.store_owner_card" type="tel"></el-input>
      </el-form-item>
      <el-form-item label="店铺名称：" prop="store_name">
        <el-input v-model="form.store_name"></el-input>
      </el-form-item>
      <el-form-item label="店铺简称：">
        <el-input v-model="form.store_abbr"></el-input>
      </el-form-item>
       <el-form-item label="所属集团：" prop="depart_id" >
        <el-select v-model="form.depart_id" placeholder="请选择" @change="handleSelectChange">
          <el-option
            v-for="item in group"
            :key="item.depart_id"
            :label="item.depart_name"
            :value="item.depart_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属分类：" prop="sc_id">
        <el-select v-model="form.sc_id" placeholder="请选择" @change="handleSelectChange">
          <el-option
            v-for="item in typeList"
            :key="item.sc_id"
            :label="item.sc_name"
            :value="item.sc_id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在地区：" required class="area">
        <el-col :span="24">
          <area-select ref="areaForm" :area_id_arr="area_id_arr" fid="0" :def_id="form.area_id" @change="updateArea"></area-select>
        </el-col>
      </el-form-item>
      <el-form-item label="经营品牌：" class="brand">
        <el-row v-if="store_brand.length > 0">
          <el-tag
            v-for="(tag, index) in store_brand"
            :key="index"
            closable
            type="info"
            size="medium"
            @close="removeBrandTags('store_brand', index)">
            {{tag.brand_name}}
          </el-tag>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-select v-model="brand[0].list[0]" placeholder="选择厂商" @change="changeBrand(0, 0)">
              <el-option v-for="(item, index) in brandArr" :key="index" :label="item.brand_initial+ ' ' + item.brand_name" :value="index"></el-option>
            </el-select>
            <el-select v-if="brand[0].list[0] >= 0" v-model="brand[0].list[1]" placeholder="选择品牌" @change="changeBrand(0, 1)">
              <el-option v-for="(item, index) in getCarBrandOptions(brand[0].list[0])" :key="index" :label="item.brand_name" :value="index"></el-option>
            </el-select>
            <el-button type="primary" @click="addBrandTags('store_brand', 0)" icon="el-icon-plus"></el-button>
            <!--el-form-item prop="brand_ids"></el-form-item-->
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="新能源商家：" class="brand">
          <!-- <el-switch 
            active-color="#13ce66"
            active-text="是"
            inactive-text="否"
            inactive-color="#ff4949" 
            v-model="form.is_new_energy" 
            :active-value="1" 
            :inactive-value="2"></el-switch> -->
            <el-select v-model="form.is_new_energy">
                <el-option value="1" label="主机厂新能源店"></el-option>
                <el-option value="2" label="元通常规店"></el-option>
                <el-option value="3" label="独立品牌新能源店"></el-option>
            </el-select>
      </el-form-item>
      <el-form-item label="服务品牌：" class="brand">
        <el-row v-if="store_service_brand.length > 0">
          <el-tag
            v-for="(tag, index) in store_service_brand"
            :key="index"
            closable
            type="info"
            size="medium"
            @close="removeBrandTags('store_service_brand', index)">
            {{tag.brand_name}}
          </el-tag>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-select v-model="brand[1].list[0]" placeholder="选择厂商" @change="changeBrand(1, 0)">
              <el-option v-for="(item, index) in brandArr" :key="index" :label="`${item.brand_initial} ${item.brand_name}`" :value="index"></el-option>
            </el-select>
            <el-select v-if="brand[1].list[0] >= 0" v-model="brand[1].list[1]" placeholder="选择品牌" @change="changeBrand(1, 1)">
              <el-option v-for="(item, index) in getCarBrandOptions(brand[1].list[0])" :key="index" :label="item.brand_name" :value="index"></el-option>
            </el-select>
            <el-button type="primary" @click="addBrandTags('store_service_brand', 1)" icon="el-icon-plus"></el-button>
            <!--el-form-item prop="service_brand_ids"></el-form-item-->
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="详细地址：" prop="store_address">
        <el-input v-model="form.store_address"></el-input>
      </el-form-item>
      <el-form-item label="邮政编码：" prop="store_zip">
        <el-input v-model="form.store_zip" type="tel"></el-input>
      </el-form-item>
      <el-form-item label="联系电话：" prop="store_tel">
        <el-input v-model="form.store_tel" type="tel"></el-input>
      </el-form-item>
      <el-form-item label="所属等级：" prop="grade_id">
        <el-select v-model="form.grade_id" placeholder="请选择">
          <el-option
            v-for="item in levelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
       
      <el-form-item label="有效期至：">
        <el-date-picker
          v-model="form.store_end_time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态：">
        <el-switch
          v-model="state"
          active-color="#13ce66"
          active-text="开启"
          inactive-text="关闭"
          inactive-color="#ff4949"
        ></el-switch>
      </el-form-item>
      <el-form-item label="使用状态：" prop="usage_status">
        <el-select v-model="form.usage_status" placeholder="请选择">
          <el-option
            v-for="item in useStatusList"
           :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关闭原因：" v-if="!state">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入内容"
          v-model="this.form.store_close_info"
        ></el-input>
      </el-form-item>
      <el-form-item label="认证：">
        <el-checkbox-group v-model="name_auth">
          <el-checkbox label="0">实名认证</el-checkbox>
          <el-checkbox label="1">实体店铺认证</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="推荐：" prop="store_recommend">
        <el-switch
          v-model="recommend"
          active-color="#13ce66"
          active-text="是"
          inactive-text="否"
          inactive-color="#ff4949"
        ></el-switch>
        <span style="margin-left: 70px">店铺关闭时不可推荐</span>
      </el-form-item>
       <el-form-item label="督导名称：" prop="followerId">
        <el-select v-model="form.followerId" @change="selectGraderListModel($event)" placeholder="请选择">
          <el-option
            v-for="item in GraderList"
             :key="item.id"
            :label="item.superintendent"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="积分管理权限：" prop="point_power">
        <el-switch
          v-model="point_power"
          active-color="#13ce66"
          active-text="是"
          inactive-text="否"
          inactive-color="#ff4949"
        ></el-switch>
      </el-form-item>
      <el-form-item label="商品最低利润率：" prop="min_profit_rate">
        <el-input 
          type="text" placeholder="" v-model="form.min_profit_rate" class="goods-price-lrl" @input="handlePriceLrl" maxlength="5">
        </el-input> % 
        <span class="color-info">备注：店铺上架商品，上架价格 需要大于 协议价 *（1+最低利润率）</span>
      </el-form-item>
      <el-form-item label="小程序归属：" prop="belong_project">
        <el-select v-model="form.belong_project" placeholder="请选择">
          <el-option
            v-for="item in belongProject"
           :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序：" prop="name">
        <el-input v-model="form.store_sort"></el-input>
      </el-form-item>
   
         <el-form-item   label-width="140px" label="企微客户数据统计：">
        <el-switch
          v-model="wechat_state"
          active-color="#13ce66"
          active-text="开启"
          inactive-text="关闭"
          inactive-color="#ff4949"
        ></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import AreaSelect from "@/components/home/area.vue";
import { resize } from "@/common/js/height.js";
import { filterNumber } from '@/common/js/util.js'

export default {
  props: {},
  components: {AreaSelect},
  data() {
    return {
      // 表单验证
      rules: {
        grade_id: {
          required: true,
          message: "请选择店铺等级",
          trigger: "change"
        },
        store_name: {
          required: true,
          message: "请填写店铺名称",
          trigger: "blur"
        },
        sc_id: { required: true, message: "请选择所属分类", trigger: "change" },
        depart_id: {
          required: true,
          message: "请选所属集团",
          trigger: "change"
        },
        brand_ids: {
          required: true,
          message: "请添加经营品牌"
        },
        service_brand_ids: {
          required: true,
          message: "请添加服务品牌"
        }
      },
      // 表单数据
      form: {
        depart_id: "",
        member_name: "",
        member_id: "",
        store_name: "",
        store_id: "",
        grade_id: "",
        store_owner: "",
        store_owner_card: "",
        sc_id: "",
        store_address: "",
        store_zip: "",
        store_tel: "",
        store_state: true,
        name_auth: [],
        store_auth: "",
        store_sort: 0,
        store_type: "",
        store_end_time: "",
        store_recommend: true,
        store_close_info: "",
        min_profit_rate: "",
        province_id: "",
        province_name: "",
        city_id: "",
        city_name: "",
        area_id: "",
        area_name: "",
        county_id: "",
        county_name: "",
        town_id: "",
        town_name: "",
        area_info: "",
        store_abbr:"",
        usage_status:"",
        follower:"",
        followerId:"",
        brand_ids: [],
        service_brand_ids: [],
        belong_project: '0',
        store_point_power: 0, // 积分管理权限
        is_new_energy:'2',
      },
      typeList: [], //店铺分类
      levelList: [], //店铺等级
      GraderList: [], //督导
      useStatusList: [], //使用状态
      name_auth: [],
      state: true,
      wechat_state:true,//企微客户数据统计 1开启0关闭
      recommend: true,
      group: [],
      brandArr: [], // 品牌分类,
      brand: [{list: [], brand_id: "", brand_name: ""}, {list: [], brand_id: "", brand_name: ""}],
      point_power: false, // 积分管理权限
      store_brand: [], // 经营品牌,
      store_service_brand: [], // 服务品牌,
      area_id_arr: ['province', 'city', 'county', 'town'],
      belongProject: [
        {label: '请选择', value: '0'},
        {label: '元通汽车小程序', value: '1'},
        {label: '数字4S店小程序', value: '2'},
      ]
    };
  },
  created() {
    this.getGroup();         // 获取集团
    this.getType();          // 获取分类
    this.getLevel();         // 获取等级
    this.getGraderList();    // 督导
    this.getUseStatusList(); // 获取状态
    this.getCarBrand();      // 获取厂品牌
    resize(this);
    // this.area = nc_a;        // 获取省市区
    // 有name 是新增，没有是 修改
    if (this.$route.query.name) {
      this.form.member_name = this.$route.query.name;
      this.form.member_id = this.$route.query.id;
    } else {
      this.form.store_id = this.$route.query.id;
      this.getInfo();
    }
  },
  computed: {
    getCarBrandOptions() {
      return function(index = 0) {
        return this.brandArr[index].details;
      }
    }
  },
  methods: {
    updateArea(area = {}) {
      for(let [index, value] of Object.entries(area)) {
        this.form[index + '_id'] = value.id;
        this.form[index + '_name'] = value.name;
      }
    },
    // 获取品牌数据
    getCarBrand() {
      // this.$http.post('/admin/yt_car/index.php?act=yt_car&op=getBrandList', {}).
      this.$http.post('/admin/store/index.php?act=getBrand&op=selectBrand', {fid: 1}).
      then(res => {
          this.brandArr = res || [];
      })
    },
    // 品牌选择
    changeBrand(key = 0, index = 0) {
      if(index == 0) {
        this.brand[key].list = [this.brand[key].list[0]];
        let _brand = this.brandArr[this.brand[key].list[0]];
        this.brand[key].brand_id = _brand.brand_id;
        this.brand[key].brand_name = _brand.brand_name;
        if(!_brand.details) {
          this.$http.post('/admin/store/index.php?act=getBrand&op=selectBrand', {fid: this.brandArr[this.brand[key].list[0]].brand_id}).
          then(res => {
            this.$set(this.brandArr[this.brand[key].list[0]], 'details', res)
          })
        }
      } else if(index == 1) {
        const _brand = this.brandArr[this.brand[key].list[0]].details[this.brand[key].list[1]];
        this.brand[key].brand_name = _brand.brand_name;
        this.brand[key].brand_id = _brand.brand_id;
      }
    },
    // 添加品牌标签
    addBrandTags(type = "store_brand", key = 0) {
      if(!this.brand[key].brand_name) {
        this.$message.error("请选择产商")
        return;
      }

      let _brand = this.store_brand, _brand_ids = this.form.brand_ids, _brand_ids_key = "brand_ids";
      if(type == 'store_service_brand') {
        _brand = this.store_service_brand;
        _brand_ids = this.form.service_brand_ids;
        _brand_ids_key = "service_brand_ids";
      }

      // 判断是否重复添加
      if(_brand_ids.includes(this.brand[key].brand_id)) {
        this.$message.error("重复添加")
        return;
      }

      // 添加
      _brand.push({
        brand_id: this.brand[key].brand_id,
        shop_id: this.form.store_id,
        brand_name: this.brand[key].brand_name
      })
      _brand_ids.push(this.brand[key].brand_id)

      // 移除校验
      this.$refs.ruleForm.clearValidate(_brand_ids_key);

      // 去重
      // let set = new Set(store_brand);
      // this.form[type] = [...set];
    },
    // 删除品牌标签
    removeBrandTags(type = "store_brand", index = 0) {
      let _brand = this.store_brand, _brand_ids = this.form.brand_ids, brand_type = 0;
      if(type == 'store_service_brand') {
        _brand = this.store_service_brand;
        _brand_ids = this.form.service_brand_ids;
        brand_type = 1;
      }
      const datas = {brand_id: _brand_ids[index], store_id: this.form.store_id, brand_type }
      this.$http.post("/admin/store/index.php?act=storeManage&op=delBrand", datas).then(res => {
        if(res.code == 1 || res.code == 404) {
          _brand.splice(index, 1);
          _brand_ids.splice(index, 1);
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    selectGraderListModel(id){
      let obj = {};
      obj = this.GraderList.find((item)=>{//model就是上面的数据源
          return item.id === id;//筛选出匹配数据
      });
      this.form.follower=obj.superintendent;
    },
    // 获取店铺分类
    getType() {
      this.$http
        .post("/admin/store/index.php?act=storeManage&op=storeCategories")
        .then(res => {
          if (res.code == "1") {
            this.typeList = res.data;
          }
        });
    },
     ///督导
    getGraderList() {
      this.$http
        .post("/admin/store/index.php?act=storeManage&op=getFollowerSelect")
        .then(res => {
          if (res.code == "1") {
            this.GraderList = res.data;


          }
        });
    },
      //获取状态
    getUseStatusList() {
      this.$http
        .post("/admin/store/index.php?act=storeManage&op=getUsageStatus")
        .then(res => {
          if (res.code == "1") {
            this.useStatusList = res.data;
          }
        });
    },
    // 获取店铺等级
    getLevel() {
      this.$http
        .post("/admin/store/index.php?act=storeManage&op=storeGrades")
        .then(res => {
          if (res.code == "1") {
            this.levelList = res.data;
          }
        });
    },
    handleSelectChange() {
      // const { depart_id, sc_id } = this.form
      // if (sc_id == 65) {
      //   this.form.belong_project = depart_id == 600 ? '1' : '2'
      // }
    },
    // 提交
      async submit() {
      // 验证表单
      await new Promise((resolve, reject) => {
        this.$refs['areaForm'].$refs['elArea'].validate(valid => {
          if(valid) resolve();
        })
      })
      await this.$refs.ruleForm.validate(valid => {
      
        if (valid) {
          this.form.area_info =
            this.form.province_name + this.form.city_name + this.form.county_name + this.form.town_name;
          this.form.store_recommend = this.recommend ? 1 : 0;
          this.form.store_state = this.state ? 1 : 0;
           this.form.wechat_state = this.wechat_state ? 1 : 0;//1开启0关闭
          this.form.name_auth =
            this.name_auth.findIndex(value => value == 0) == -1 ? 0 : 1;
          this.form.store_auth =
            this.name_auth.findIndex(value => value == 1) == -1 ? 0 : 1;
          //this.form.store_brand = this.form.store_brand.join(",");
          this.form.store_point_power = this.point_power ? 1 : 0;
          this.form.brand_ids = this.form.brand_ids;
          this.form.service_brand_ids = this.form.service_brand_ids;
          this.form.area_id = this.form.town_id ? this.form.town_id : this.form.county_id;
          this.form.belong_project = this.form.belong_project ? this.form.belong_project : 0;
          this.$http
            .post(
              "/admin/store/index.php?act=storeManage&op=addStore",
              this.form
            )
            .then(res => {
              if (res.code == 1) {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: "success"
                });
                this.$router.replace({
                  path: "shop-edit"
                });
                this.$router.go(-1);
              } else {
                this.$message({
                  showClose: true,
                  message: res.msg,
                  type: "error"
                });
              }
            });
        }
      });
    },
    handlePriceLrl(val) {
      this.form.min_profit_rate = filterNumber(val, 0)
    },
    // 获取集团列表
    getGroup() {
      this.$http
        .post("/admin/depart/index.php?act=departManage&op=firstDeparts")
        .then(res => {
          if (res.code == 1) {
            this.group = res.data;
          }
        });
    },
    // 获取店铺详情
    getInfo() {
      this.$http
        .post("/admin/store/index.php?act=storeManage&op=storeDetail", {
          store_id: this.form.store_id
        })
        .then(res => {
          if (res.code == 1) {
            this.form.depart_id = res.data.depart_id + "";
            this.form.member_name = res.data.member_name;
            this.form.member_id = res.data.member_id;
            this.form.store_name = res.data.store_name;
            this.form.grade_id = res.data.grade_id;
            this.form.store_owner = res.data.store_owner;
            this.form.store_owner_card = res.data.store_owner_card;
            this.form.sc_id = res.data.sc_id;
            this.form.store_zip = res.data.store_zip;
            this.form.store_tel = res.data.store_tel;
            this.form.store_sort = res.data.store_sort;
            this.form.store_type = res.data.store_type;
      
            this.form.store_abbr = res.data.store_abbr;
            this.form.usage_status = res.data.usage_status;
            this.form.followerId = res.data.followerId;
            this.form.follower = res.data.follower;
            this.point_power = parseInt(res.data.store_point_power) == 1 ? true : false;
            this.store_brand = res.data.store_brand || [];
            this.form.brand_ids = this.store_brand.map(item => {
              return item.brand_id;
            })
            this.store_service_brand = res.data.store_service_brand || [];
            this.form.service_brand_ids = this.store_service_brand.map(item => {
              return item.brand_id;
            })
           
            // 结束时间
            this.form.store_end_time = res.data.store_end_time;
            // 店铺状态
            this.form.store_state = res.data.store_state;
            this.state = res.data.store_state == 1 ? true : false;
            this.wechat_state = res.data.wechat_state == 1 ? true : false;
            // 推荐
            this.form.store_recommend = res.data.store_recommend;
            this.recommend = res.data.store_recommend == 1 ? true : false;
            //关闭原因
            this.form.store_close_info = res.data.store_close_info;
            this.form.min_profit_rate = res.data.min_profit_rate;
            // 详细地址
            this.form.store_address = res.data.store_address;

            // 省市县
            this.form.area_id = res.data.area_id;
            this.form.area_info = res.data.area_info;

            // 实名认证和实名店铺认证
            this.form.name_auth = res.data.name_auth;
            this.form.store_auth = res.data.store_auth;
            if (res.data.name_auth == 1) {
              this.name_auth.push("0");
            }
            if (res.data.store_auth == 1) {
              this.name_auth.push("1");
            }
              this.form.belong_project = res.data.belong_project;
              this.form.is_new_energy = res.data.is_new_energy ? res.data.is_new_energy : 2
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error"
            });
          }
        });
    }
  }
};
</script>

<style scoped lang="scss">
.shop-edit {
  padding: 20px 20px 20px 20px;
  .el-input,
  .el-select,
  .el-cascader,
  .el-textarea {
    width: 220px;
  }
  .brand {
    /deep/.el-select.el-select--mini {
      margin-right: 8px;
      width: 168px;
      .el-input {
        width: 100%;
      }
    }
    .el-form-item--mini.el-form-item {
      margin-bottom: 0;
    }
    .el-tag.el-tag--info {
      background-color: #fff;
      border-color: #e9e9eb;
      color: #333;
      margin: 0 8px 8px 0;
    }
    /deep/.el-tag--medium .el-icon-close {
      -webkit-transform: scale(1);
      transform: scale(1);
    }
  }
}
.el-select-dropdown__item {
  font-size: 12px;
}
.el-input.goods-price-lrl {
  width: 80px;
  + span { margin-left: 10px; }
}
</style>
